package com.google.coffeeshop.gui.desktop.selfcomponent;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import vn.bang.utility.ImageUtil;

public class ImagePanel extends JPanel{
	private static final long serialVersionUID = 1L;
	private BufferedImage imageBuff;
	private boolean fit = Boolean.FALSE;

    public ImagePanel(boolean fit) {
    	this.fit = fit;
    }

    public void setImage(String imagePath) {
    	try {                
    		imageBuff = ImageIO.read(new File(imagePath));
         } catch (IOException ex) {
              // handle exception...
         }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (imageBuff == null) {
        	return;
        }
        if (fit) {
        	double scaleFactor = Math.min(1d, ImageUtil.getScaleFactorToFit(new Dimension(imageBuff.getWidth(), imageBuff.getHeight()), getSize()));

            int scaleWidth = (int) Math.round(imageBuff.getWidth() * scaleFactor);
            int scaleHeight = (int) Math.round(imageBuff.getHeight() * scaleFactor);

            Image scaled = imageBuff.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);

            int width = getWidth() - 1;
            int height = getHeight() - 1;

            int x = (width - scaled.getWidth(this)) / 2;
            int y = (height - scaled.getHeight(this)) / 2;

            g.drawImage(scaled, x, y, this);
        } else {
        	g.drawImage(imageBuff, 0, 0, null);
        }
    }
}
